﻿using CRM.Models;
using CRM.ViewModels.User;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;

namespace CRM.Extensions
{
    public static class AuthItem
    {
        public static object GetAuthItem(this IEnumerable<Menu> MenuList, ILogger logger = null)
        {
            var keys = MenuList.Where(m => m.Has).Where(m => m.ParentId != null).Select(m => m.Id);

            Dictionary<int, List<AuthItemData>> dic = new();
            foreach (var menu in MenuList)
            {
                AuthItemData ai = new(menu);
                var key = menu.ParentId.GetValueOrDefault();
                if (!dic.ContainsKey(key))
                {
                    dic.Add(key, new());
                }
                dic[key].Add(ai); ;
            }
            List<AuthItemData> Temp = null;
            if (dic.ContainsKey(0))
            {
                foreach (var item in dic[0])
                {
                    var key = item.id;
                    if (dic.ContainsKey(key))
                    {
                        item.children = dic[key];
                    }
                }
                Temp = dic[0];
            }
            else
            {
                logger?.LogWarning("未发现顶级菜单");
                return null;
            }
            return new { list = Temp, keys = keys };
        }
       
    }
}
